<?php

namespace ShineYork\LaravelExtend\Swoole\Server;

// swoole的服务类
// swoole服务的管理
use Illuminate\Contracts\Container\Container;
use ShineYork\LaravelExtend\Swoole\Http\SRequest;
use Illuminate\Contracts\Http\Kernel;
use ShineYork\LaravelExtend\Swoole\Http\SResponse;

class Manager
{
    // 事件 =>只是服务中某一个点

    //对swoole的事件进行处理
    //启动的操作
    //保存laravel application

    /**
     * 保存swoole服务
     * @var \Swoole\Http\Server | \Swoole\WebSocket\Server
     */
    protected $server;

    /**
     * laravel application
     * @var
     */
    protected $laravel;

    /**
     * swoole事件
     * @var
     */
    protected $events = [
        'http' => [
            //swoole监听事件 =》 当前类中对应的监听方法
            'request' => 'onRequest'
        ],
        'webSocket' => []
    ];

    public function __construct(Container $laravel)
    {
       $this->laravel = $laravel;
       //获取swoole服务
       $this->server = $this->laravel->make('extend.swoole_server');

       //设置swoole监听函数
       $this->setSwooleServerEvents();
    }

    public function setSwooleServerEvents()
    {
        $type = config('extend.swoole.server_type') ? 'http' : 'websocket';
        foreach ($this->events[$type] as $event => $func) {
            $this->server->on($event, [$this, $func]);
        }
    }

    public function run()
    {
        $this->server->start();
    }

    /**
     * swoole执行的处理闭包
     * @param $request
     * @param $response
     */
    public function onRequest($swooleRequest, $swooleResponse)
    {
        $laravelRequest = SRequest::make($swooleRequest);
        $laravelResponse = $this->laravel->make(Kernel::class)->handle($laravelRequest);

        SResponse::make($laravelResponse, $swooleResponse)->send();

        //$swooleResponse->end($laravelResponse->getContent());
    }
}
